package com.polaris.live.dialog

import android.content.Context
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.databinding.DialogRoomBackgroundBuyBinding
import com.polaris.live.popup.DiscountPopup
import com.polaris.live.resp.back_resp.UserBackpackConsumableResp
import com.polaris.live.translation.R.string
import com.polaris.live.utils.image.ImageUtils

/**
 * 使用自定义房间背景卡弹窗
 *
 * @author Created by 半仙 on 2024/12/20/020 14:12
 */
class RoomBackgroundBuyDialog(
    context: Context,
    private val mDecorationList: MutableList<UserBackpackConsumableResp>,
    private val callback: (data: UserBackpackConsumableResp?) -> Unit,
    private val onBuyCallback: () -> Unit,
) : CenterPopupView(context) {

    override fun getImplLayoutId() = R.layout.dialog_room_background_buy

    private lateinit var mBinding: DialogRoomBackgroundBuyBinding

    private var mNowData: UserBackpackConsumableResp? = null

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogRoomBackgroundBuyBinding.bind(popupImplView)
        val item = mDecorationList.getOrNull(0) ?: return
        setUi(item)
        initListener()
    }

    private fun initListener() {
        mBinding.dressDiscountCouponCl.setOnSingleClickListener {
            DiscountPopup.show(
                context,
                StringUtils.getString(string.custom_background_card),
                mDecorationList,
                false
            ) {
                it?.let { it1 -> setUi(it1) }
            }
        }
        mBinding.tvCancel.setOnSingleClickListener {
            onBuyCallback.invoke()
            dismiss()
        }
        mBinding.tvUse.setOnSingleClickListener {
            mNowData?.let { callback.invoke(it) }
            dismiss()
        }
    }

    private fun setUi(item: UserBackpackConsumableResp) {
        mNowData = item
        mBinding.apply {
            tvName.text = "${item.name}"
            dressDiscountCouponTv.text = item.name
            Glide.with(context).load(ImageUtils.imgPath(item.displayUrl)).into(ivToolCard)
            Glide.with(context).load(ImageUtils.imgPath(item.displayUrl)).into(discountImg)
        }
    }

    companion object {

        fun show(
            context: Context,
            mDecorationList: MutableList<UserBackpackConsumableResp>,
            callback: (data: UserBackpackConsumableResp?) -> Unit,
            onBuyCallback: () -> Unit,
        ) {
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .asCustom(RoomBackgroundBuyDialog(context, mDecorationList, callback, onBuyCallback))
                .show()
        }
    }
}